from django.shortcuts import render
from cart import models,sercart
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.authentication import JWTAuthenticationss

# Create your views here.

class AddCart(APIView):
    # authentication_classes = [JWTAuthenticationss]
    def post(self,request):
        data = models.Cart.objects.filter(user_id=request.data.get('user'),course_id=request.data.get('course')).first()
        if data:
            return Response({'code': 200, 'msg': '已存在'})

        models.Cart.objects.create(user_id=request.data.get('user'),course_id=request.data.get('course'))
        return Response({'code': 200, 'msg': '添加成功'})


class Cartlist(APIView):
    # authentication_classes = [JWTAuthenticationss]
    def get(self,request):
        data = models.Cart.objects.filter(user_id=request.query_params.get('userid'))
        return Response({'code': 200, 'msg': '查询成功', 'data': sercart.CartSerializer(data, many=True).data})

class Cartdel(APIView):
    # authentication_classes = [JWTAuthenticationss]
    def post(self,request):
        models.Cart.objects.filter(id=request.data.get('id')).delete()
        return Response({'code': 200, 'msg': '删除成功'})

class Cartupdate(APIView):
    # authentication_classes = [JWTAuthenticationss]
    def post(self,request):
        id = request.data.get('id')
        is_selected = request.data.get('selected')
        models.Cart.objects.filter(id=id).update(is_selected=is_selected)
        return Response({'code': 200, 'msg': '修改成功'})


class Cartall(APIView):
    # authentication_classes = [JWTAuthenticationss]
    def post(self,request):
        id=request.data.get('id')
        selected=request.data.get('selected')
        choseall=models.Cart.objects.filter(user_id=id)
        if selected:#全选
            for i in choseall:
                i.is_selected=True
                i.save()
        else:#全不选
            for i in choseall:
                i.is_selected=False
                i.save()
        return Response({'code': 200, 'msg': '修改成功'})


class Cartdelchose(APIView):
    # authentication_classes = [JWTAuthenticationss]
    def post(self,request):
        userid=request.data.get('userid')
        models.Cart.objects.filter(user_id=userid,is_selected=True).delete()
        return Response({'code': 200, 'msg': '删除成功'})